import { AfterViewInit, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { FormService } from '@core/services/form.service';
import { deepClone, exists, getO } from '../../../utils/utils';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { Events } from '@core/services/events/Events';
import { UserAuthService } from '@core/services/user-auth.service';
import { ButtonService, ButtonType } from '@core/services/button.service';

@Component({
  selector: 'inquiry-sheet',
  templateUrl: './inquiry-sheet.component.html',
  // styleUrls: ['./inquiry-sheet.component.scss'],
})
export class InquirySheetComponent implements OnInit, AfterViewInit {

  ctx = { model: {} };
  buttonBar = [
    { hide: true, style: 'primary', label: '发起询价', id: 'action_submit', loading: false, disabled: false },
  ];

  customerCar: any;
  customerCarApi: any = 'fn.customerCar.findAll';
  customerCarDomain: any = {
    'filters': [
      { 'field': 'carLicense', 'operator': 'LIKE', 'value': '{{value}}' },
      { 'field': 'mobile', 'operator': 'LIKE', 'value': '{{value}}' },
      { 'field': 'realname', 'operator': 'LIKE', 'value': '{{value}}' },
    ],
    'groups': [],
    'operator': 'or',
  };

  inputVIN: string = ''; // LFMARE2C4D0397522
  isLoading: boolean = false;
  isQueryLoading: boolean = false;

  form = new FormGroup({});
  carModel: any = {};
  carField: FormlyFieldConfig[] = [
    {
      key: 'carLicense',
      type: 'span',
      templateOptions: {
        label: '车牌',
        divCol: 8,
      },
    },
    {
      key: 'vin',
      type: 'span',
      templateOptions: {
        label: '车架号',
        divCol: 8,
      },
    },
    {
      key: 'carBaseInfo',
      type: 'drawer',
      templateOptions: {
        label: '车型',
        divCol: 8,
        api: 'fn.api.getCustomerCarDetailInfo',
        formId: 'fn.api.getCustomerCarDetailInfo',
        valueFormatter: 'value.carLabelOrModel',
      },
    },
    //
    // {
    //   key: 'carBaseInfo.frontWheelStandard',
    //   type: 'span',
    //   templateOptions: {
    //     label: '前轮胎规格',
    //     divCol: 5,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.carLabel',
    //   type: 'span',
    //   templateOptions: {
    //     label: '厂牌',
    //     divCol: 4,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.partsCode',
    //   type: 'span',
    //   templateOptions: {
    //     label: '车型配件代码',
    //     divCol: 4,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.transmissionDescription',
    //   type: 'span',
    //   templateOptions: {
    //     label: '变速箱',
    //     divCol: 4,
    //     lblCol: 10,
    //     inputCol: 14,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.carConfiguration',
    //   type: 'span',
    //   templateOptions: {
    //     label: '型号',
    //     divCol: 7,
    //     lblCol: 4,
    //     inputCol: 20,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.engineModel',
    //   type: 'span',
    //   templateOptions: {
    //     label: '发动机型号',
    //     divCol: 3,
    //     lblCol: 14,
    //     inputCol: 10,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.transmissionModel',
    //   type: 'span',
    //   templateOptions: {
    //     label: '变速箱型号',
    //     divCol: 3,
    //     lblCol: 14,
    //     inputCol: 10,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.engineCode',
    //   type: 'span',
    //   templateOptions: {
    //     label: '发动机号码',
    //     divCol: 3,
    //     lblCol: 14,
    //     inputCol: 10,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.transmissionType',
    //   type: 'span',
    //   templateOptions: {
    //     label: '变速箱类型',
    //     divCol: 3,
    //     lblCol: 14,
    //     inputCol: 10,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.drive',
    //   type: 'span',
    //   templateOptions: {
    //     label: '驱动方式',
    //     divCol: 3,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.sweptVolume',
    //   type: 'span',
    //   templateOptions: {
    //     label: '排量',
    //     divCol: 2,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.STT',
    //   type: 'span',
    //   templateOptions: {
    //     label: '发动机启停技术',
    //     divCol: 4,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.produceYear',
    //   type: 'span',
    //   templateOptions: {
    //     label: '生产年份',
    //     divCol: 3,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.rearWheelStandard',
    //   type: 'span',
    //   templateOptions: {
    //     label: '后轮胎规格',
    //     divCol: 4,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.yearType',
    //   type: 'span',
    //   templateOptions: {
    //     label: '年款',
    //     divCol: 3,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.passengerQty',
    //   type: 'span',
    //   templateOptions: {
    //     label: '核载人数',
    //     divCol: 3,
    //     lblCol: 16,
    //     inputCol: 8,
    //   },
    // },
    // {
    //   key: 'carBaseInfo.carServiceLevelName',
    //   type: 'span',
    //   templateOptions: {
    //     label: '服务等级',
    //     divCol: 3,
    //     lblCol: 12,
    //     inputCol: 12,
    //   },
    // },
  ];

  searchTyreApi: any = 'fn.tyreEnquiryService.tyreSpecification';
  selectTyre: any;

  id: any;
  sourceFormId: any;
  queryData: any = {};

  partsModel: any = {
    value: '',
    oldValue: '',
    visible: false,
    loading: true,
    items: [],
    search: null,
    partsName: '',
    partsCodes: '',
    partsInfos: {
      pictures: null,
      otherImg: null,
      remark: '',
      otherRemark: '',
    },
    standardName: '',
  };

  partsList: any = [];
  imgType: any = 'image/png,image/jpeg,image/gif,image/bmp';

  autoSearchTime: any;
  sourceId: any;
  compilePlatform: any;

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private formService: FormService,
              private cd: ChangeDetectorRef,
              protected events: Events,
              private userAuthService: UserAuthService,
              private buttonService: ButtonService,
  ) {
  }

  ngOnInit() {
    let platform = this.userAuthService.getUserInfoObj() ? this.userAuthService.getUserInfoObj().platform : '';
    if (platform == 'zt') {
      this.customerCarDomain['filters'].push({ 'field': 'ven', 'operator': '=', 'value': '1' });
    }
  }

  ngAfterViewInit() {
    this.initData();
    this.initPartsModel();

    this.events.subscribe(this.getUrl(), data => {
      console.log('跳转数据--', data);
      this.autoSearch(data);
    });

    if (this.formService.formData.hasOwnProperty('key')) {
      let data = this.formService.formData['key'];
      console.log('跳转数据--', data);
      this.autoSearch(data);
      delete this.formService.formData['key'];
    }
  }

  // 初始化数据
  initData() {
    this.customerCar = null;
    this.carModel = {};
    this.queryData = {};
    this.inputVIN = '';
    this.partsList = [];
  }

  // 初始化查询配件
  initPartsModel() {
    this.partsModel = {
      value: '',
      oldValue: '',
      visible: false,
      loading: true,
      items: [],
      search: null,
      partsName: '',
      partsCodes: '',
      partsInfos: {
        pictures: null,
        otherImg: null,
        remark: '',
        otherRemark: '',
      },
      standardName: '',
    };
  }

  autoSearch(param) {
    let value = param.customerCar;
    let items = param.categoryIds;
    this.id = param.id;
    this.sourceFormId = param.sourceFormId;
    // this.inputVIN = param.vin;
    // this.checkVIN();
    this.checkVINData(value);


    this.autoSearchTime = setInterval(() => {
      if (!this.isLoading) {
        // console.log('跳转配件-', items);
        clearInterval(this.autoSearchTime);
        if (items && items.length != 0) {
          items.forEach((item) => {
            let name = item.name.replace(/\(/g, '（')
              .replace(/\)/g, '）');
            let partCode = item.partCode;
            let data = {
              remark: item.remark ? item.remark : '',
              otherImg: item.oldPicture ? item.oldPicture : null,
              otherRemark: item.note ? item.note : '',
              fourSPrice: item.fourSPrice ? item.fourSPrice : null,
              productId: item.productId ? item.productId : null,
            };
            if (partCode) {
              if (name == '待编译') {
                data['partsName'] = partCode;
                this.searchPartsDetails(null, data, true);
              } else if (name == '轮胎') {
                data['partCode'] = partCode;
                data['typeTag'] = 'tyre';
                data['edit'] = false;
                this.addPartsList({ NAME: partCode }, data, 1);
                this.partsListSort();
              } else {
                data['partCode'] = partCode;
                this.addPartsList(name, data, 1);
                this.partsListSort();
              }
            } else if (item.productRule) {
              data['typeTag'] = 'refit';
              data['edit'] = false;
              data['partCode'] = item.productName;
              this.addPartsList(name, data, 1);
              this.partsListSort();
              return;
            } else {
              data['partsName'] = name;
              this.searchPartsDetails(null, data, true);
            }
          });
        }
      }
    }, 1000);
  }

  // 查车牌带出vin
  checkVINData(value) {
    // console.log('车牌---', value);
    this.initData();
    this.initPartsModel();
    if (value) {
      this.customerCar = value;
      this.inputVIN = value.vin;
      this.checkVIN();
    }

  }

  checkQueryData() {
    let show = Object.keys(this.queryData).length == 0;
    return show;
  }

  // 查询vin
  checkVIN() {
    if (!this.inputVIN) return;
    // let api = 'sp.baturuCodingService.queryCarTypeByVin';
    let api = 'sp.compileService.queryCarTypeByVin';  // 金池
    let setData = {
      vinCode: this.inputVIN,
    };
    this.isLoading = true;
    this.apiService.post(api, setData).subscribe((body) => {
      // console.log('车辆信息--', body);
      if (body) {
        this.queryData = body.model;
        this.compilePlatform = body.compilePlatform;
        this.checkCar();
      }
      this.isLoading = false;
    });
  }

  checkCar() {
    let api = 'fn.api.getCustomerCarDetailInfo';
    let setData = {
      conditionModel: this.customerCar,
      carLicense: this.customerCar.carLicense,
      compilePlatform: this.compilePlatform,
    };
    this.apiService.post(api, setData).subscribe((body) => {
      // console.log('车辆详细信息--', body);
      if (body) {
        body.carBaseInfo['carLicense'] = this.customerCar.carLicense;
        this.carModel = { ...body, ...this.customerCar };
      }
    });
  }

  checkPartsName(param, num = 0) {
    let value = param.value;
    if (num === 0 && this.partsModel['value'] == value) {
      num += 1;
    }
    if (this.partsList.length != 0) {
      this.partsList.forEach((parts) => {
        if (parts.value == value) {
          num += 1;
        }
      });
    }
    return num > 1;
  }

  checkTyrePartsName(param, num = 0) {
    let partsCodes = param.partsCodes;
    if (num === 0 && this.selectTyre == partsCodes) {
      num += 1;
    }
    if (this.partsList.length != 0) {
      this.partsList.forEach((parts) => {
        if (parts.partsCodes == partsCodes) {
          num += 1;
        }
      });
    }
    return num > 1;
  }

  // 输入配件名称
  checkParts(value, param) {
    // console.log('输入文本--', value);
    setTimeout(() => {
      let exp = /[^a-zA-Z0-9\u4e00-\u9fa5()（）]/g;
      let input = value.replace(exp, '')
        .replace(/\(/g, '（')
        .replace(/\)/g, '）');
      // console.log('输出文本--', value);
      param.value = deepClone(input);
      this.cd.markForCheck();
      this.checkFocus(param);
    }, 1);
  }

  checkRootIn(param) {
    let rootIn = param.rootIn;
    let disabled = false;
    if (rootIn != 0) {
      disabled = true;
    }
    return disabled;
  }

  showCarModel() {
    return true;
    // let show = Object.keys(this.carModel).length == 0;
    // return !show;
  }

  showPartsName(param) {
    let show = '';
    if (param['standardName'] != '') {
      show = param['standardName'];
    } else {
      if (param['typeTag'] == 'common') {
        show = param['partsName'];
      }
      if (param['typeTag'] == 'tyre') {
        show = '轮胎';
      }
      if (param['typeTag'] == 'refit') {
        show = '';
      }
    }
    return show;
  }

  // 粘贴文本
  onPaste(e: ClipboardEvent, param) {
    e.stopPropagation();
    e.preventDefault();
    const clipboardData = e.clipboardData || window['clipboardData'];
    const pastedText = clipboardData.getData('text');
    // console.log('输入原文本--', pastedText);
    const pattern = /\n/;
    // const result = pattern.test(pastedText);
    const result = true;
    if (result) {
      let items = pastedText.replace(/\n/g, ',')
        .replace(/\r/g, '')
        .replace(/\s/g, '')
        .replace(/\(/g, '（')
        .replace(/\)/g, '）')
        .split(',')
        .filter((v) => {
          return v !== '';
        });
      // console.log('items--', items);
      if (items && items.length != 0) {
        items.forEach((data) => {
          let item = {
            partsName: data,
            otherImg: null,
            otherRemark: '',
          };
          this.searchPartsDetails(param, item, true);
        });
      }
    } else {
      this.checkParts(pastedText, param);
    }
  }

  enterPares(e, param) {
    // console.log(e);
    e.stopPropagation();
    e.preventDefault();
    if (param.value == '') return;
    let item = {
      partsName: param.value,
      otherImg: null,
      otherRemark: '',
    };
    this.searchPartsDetails(param, item, true);
  }

  // 触发焦点
  checkFocus(param) {
    let value = param.value;
    let oldValue = param.oldValue;
    if (value != '' && value != undefined) {
      param.visible = true;
      if (value == oldValue) {
        param.loading = false;
      } else {
        param.loading = true;
        param['standardName'] = '';
        param['partsName'] = '';
        param['partsCodes'] = '';
        if (param['partsInfos']['otherRemark'] || param['partsInfos']['otherImg']) {
          let partsInfos = param['partsInfos'];
          param['partsInfos'] = {
            pictures: null,
            otherImg: partsInfos['otherImg'] ? partsInfos['otherImg'] : null,
            remark: '',
            otherRemark: partsInfos['otherRemark'] ? partsInfos['otherRemark'] : '',
            edit: false,
          };
        } else {
          param['partsInfos'] = {};
        }

        if (param.search) {
          clearTimeout(param.search);
        }
        param.search = setTimeout(() => {
          this.searchPartsName(param, value, 1);
        }, 500);
      }
    } else {
      param.visible = false;
      if (param.search) {
        clearTimeout(param.search);
      }
      param.items = [];
    }
  }

  // 关闭列表
  closeList(param, e?) {
    if (e) {
      setTimeout(() => {
        param.visible = false;
      }, 500);
    } else {
      param.visible = false;
    }
  }

  // 选择配件
  selectParts(param, item, isAdd) {
    this.searchPartsDetails(param, item, isAdd);
    // console.log(item);
    this.closeList(param);
  }

  // 查询配件名称
  searchPartsName(param, keyword, index) {
    param.loading = true;
    // let api = 'sp.baturuCodingService.searchPartsHintsInfo';
    let api = 'sp.compileService.searchPartsHintsInfo';  // 金池
    let setData = {
      vinCode: this.inputVIN,
      keyword: keyword,
      compilePlatform: this.compilePlatform,
    };
    param.items = [];
    this.apiService.post(api, setData).subscribe((body) => {
      // console.log('配件信息--', body);
      param.loading = false;
      param.oldValue = deepClone(keyword);
      if (body) {
        param.items = body.model;
        if (param.items.length != 0 && param.value == body.model[0]['partsName']) {
          let item = param.items[0];
          this.searchPartsDetails(param, item, false);
        }
      }
    });
  }

  // 查询配件详情
  searchPartsDetails(param, item, isAdd) {
    let carTypeIds = this.queryData.carTypeIds;
    let vinAnalyseSource = this.queryData.vinAnalyseSource;
    let partsNames = [this.transformString(item.partsName)];
    let setData = {
      vinCode: this.inputVIN,
      carTypeIds: carTypeIds,
      vinAnalyseSource: vinAnalyseSource,
      partsNames: partsNames,
      brandName: this.queryData.sameCarType.brandName,
      partsCode: item['partsCode'],
      compilePlatform: this.compilePlatform,
    };
    // console.log('配件详细入参--', setData);

    let partsName = this.transformString(item['partsName']);
    if (isAdd) {
      this.initPartsModel();
      this.addPartsList(partsName, item, 0);
      this.partsListSort();
      this.checkPartsDetailsData(setData, (data) => {
        for (let i = 0; i < this.partsList.length; i++) {
          let list = deepClone(this.partsList[i]);
          if (list['partsName'] == partsName) {
            list['loading'] = false;
            list = { ...list, ...data };
            if (!list['partsInfos'].hasOwnProperty('pictures')) {
              list['partsInfos']['pictures'] = null;
            }
            list['partsInfos']['otherImg'] = item['otherImg'] ? item['otherImg'] : null;
            list['partsInfos']['otherRemark'] = item['otherRemark'] ? item['otherRemark'] : '';
            this.partsList[i] = list;
            // console.log('详细信息结构--', list);
          }
        }
      });
    } else {
      param['value'] = partsName;
      param['partsName'] = partsName;
      param['partsCodes'] = '';
      if (param['partsInfos']['otherRemark'] || param['partsInfos']['otherImg']) {
        let partsInfos = param['partsInfos'];
        param['partsInfos'] = {
          pictures: null,
          otherImg: partsInfos['otherImg'] ? partsInfos['otherImg'] : null,
          remark: '',
          otherRemark: partsInfos['otherRemark'] ? partsInfos['otherRemark'] : '',
          edit: false,
        };
      } else {
        param['partsInfos'] = {};
      }
      param['standardName'] = '';
      param['loading'] = true;
      this.checkPartsDetailsData(setData, (data) => {
        param['loading'] = false;
        param['partsCodes'] = data['partsCodes'];
        param['standardName'] = data['standardName'];
        if (param['partsInfos']['otherRemark'] || param['partsInfos']['otherImg']) {
          param['partsInfos'] = { ...param['partsInfos'], ...data['partsInfos'] };
        } else {
          param['partsInfos'] = { ...data['partsInfos'] };
          param['partsInfos']['otherImg'] = null;
          param['partsInfos']['otherRemark'] = '';
          param['partsInfos']['edit'] = false;
        }

        // console.log('详细信息结构--', param);
        this.cd.markForCheck();
      });
    }
  }

  transformString(str) {
    if (this.isChinese(str)) {
      return str;
    }
    if (str.length >= 4) {
      return str.toUpperCase();
    }
    return str;
  }

  isChinese(str) {
    return /[\u4e00-\u9fa5]/.test(str);
  }

  // 添加配件
  addPartsList(partsName, item, rootIn) {
    let parts = {
      value: partsName,
      oldValue: '',
      visible: false,
      loading: true,
      items: [],
      search: null,
      partsName: partsName,
      partsCodes: item['partCode'] ? item['partCode'] : '',
      partsInfos: {
        pictures: null,
        otherImg: item['otherImg'] ? item['otherImg'] : null,
        remark: item['remark'] ? item['remark'] : '',
        otherRemark: item['otherRemark'] ? item['otherRemark'] : '',
        edit: item['infoEdit'] ? item['infoEdit'] : true,
        price: item['fourSPrice'] ? item['fourSPrice'] : null,
      },
      standardName: '',
      edit: item.hasOwnProperty('edit') ? item['edit'] : true,
      rootIn: rootIn, //
      typeTag: item['typeTag'] ? item['typeTag'] : 'common',
      productId: item.productId ? item.productId : null,
    };
    this.partsList.unshift(parts);
  }

  // 查询配件详情明细
  checkPartsDetailsData(setData, callback) {
    // let api = 'sp.baturuCodingService.queryPartsCodeInfo';
    let api = 'sp.compileService.queryPartsCodeInfo';  // 金池
    this.apiService.post(api, setData).subscribe((body) => {
      if (body && body.hasOwnProperty('model')) {
        // console.log('配件详细信息--', body.model);
        callback(body.model[0]);
      }
    });
  }

  // 配件列表排序
  partsListSort() {
    let length = this.partsList.length;
    for (let i = 0; i < length; i++) {
      this.partsList[i]['num'] = length - i;
    }
  }

  showOtherImg(param) {
    if (param.otherImg && param.otherImg.length != 0) {
      return true;
    } else {
      return param.edit;
    }
  }

  checkEdit(param) {
    param.edit = !param.edit;
  }

  addTyreData(value) {
    if (!value) return;
    let data = {
      otherImg: null,
      otherRemark: '',
      typeTag: 'tyre',
      partCode: value['NAME'],
    };
    this.addPartsList(value, data, 2);
    this.partsListSort();
    setTimeout(() => {
      this.selectTyre = {};
      this.cd.detectChanges();
    }, 100);
  }

  checkData(value, param) {
    if (!value) return;
    param['partsCodes'] = value['NAME'];
    param['partName'] = value;
    // this.cd.detectChanges();
    // setTimeout(()=>{
    //   param['partCode'] = value['NAME'];
    // },500)
  }

  checkImgData(value, param, key) {
    param[key] = value;
  }

  removeParts(index) {
    this.partsList.splice(index, 1);
    this.partsListSort();
  }

  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_submit') {
        if (this.partsList.length == 0) {
          this.msg.error('请先选择询价配件！！');
          return;
        }
        this.buttonBar[0].disabled = true;
        this.cd.detectChanges();
        this.submit();
      }
    }
  }

  submit() {
    this.isQueryLoading = true;
    let api = 'fn.fnEnquiryService.enquiry';
    let setData = {
      customerCar: this.customerCar,
      partsList: this.partsList,
      id: this.id,
    };
    // console.log('发起询价入参--', setData);
    this.apiService.post(api, setData).subscribe((body) => {
      // console.log('发起询价结果--', body);
      if (body) {
        this.msg.success('已发起询价！');
        this.initData();
        this.initPartsModel();
        if (this.sourceFormId) {
          let api = 'form/' + this.sourceFormId;
          let data = {
            id: 'link',
            action: 'link',
            option: {
              'id': 'downItemProgress',
              'name': '询价',
              'data': { id: this.id },
              'api': api,
              'config': { 'OAInterface': false },
              'ctx': this.ctx,
            },
          };
          this.buttonService.clickButton(data);
        }
      }
      this.isQueryLoading = false;
      this.buttonBar[0].disabled = false;
      this.cd.detectChanges();
    });
  }

  private getUrl(): string {
    let url = 'custom/inquirySheet/InquirySheetComponent';
    return url;
  }
}

